<template>
  <el-form ref="smsLoginDtats" :model="smsLoginDtat" status-icon :rules="smsRules" label-width="55px"
    class="demo-ruleForm">

    <el-form-item label="手机号" prop="phone" class="capture-form-item">
      <el-input v-model="smsLoginDtat.phone" />
      <span class="capture-span" @click="smsSend">{{ str }}</span>
    </el-form-item>

    <el-form-item label="验证码" prop="code" class="username-form-item">
      <el-input v-model="smsLoginDtat.code" type="input" autocomplete="off" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(smsLoginDtats)" class="dlogin">
        登入
      </el-button>

    </el-form-item>
  </el-form>
</template>
    
<script setup>

import * as api from "../../api/users"
// 引入接口

import { reactive, ref } from 'vue'
// 引入校验函数
// 不高亮，可以删除validateUsername,validatePassword,validateCapture,
import { smsRules, useSubmitForm } from "../../composition/login/validate"
// 引入验证码弹窗体提示
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
let router = useRouter()
// 表单校验成功
let validateSuccess = () => {
  VerificationCode(smsLoginDtat.code)
  console.log('校验成功');
}
// 表单校验失败
let validateFailed = () => {
  console.log('校验失败');
}

// 登入点击事件
let submitForm = useSubmitForm(validateSuccess, validateFailed)

const loginform = ref()
const smsLoginDtats = ref()

// 注入表单数据
const smsLoginDtat = reactive({
  phone: '',
  code: '',

})

// 获取手机验证码：
let getSend = async (phone) => {
  let res = await api.getSmsApi(phone)
  console.log(res, 'getSend');

  if (!smsLoginDtat.phone) {
    alert('请输入手机号')
    // ElMessage.error('短信发送失败')
  } else {
    // ElMessage({
    //   message: '短信发送成功',
    //   type: 'success',
    // })
  }
  return res
}
// 若手机号为空则出现弹窗提示



// 手机验证码登入
let VerificationCode = async (code) => {
  let res = await api.smsApi(code)
  console.log(res, 'code');
  router.push('/')
}

let str = ref("点击发送")
let timer = ref(null)


let isopen = false
let smsSend = async () => {
  try {
    let res = await getSend(smsLoginDtat.phone)
    console.log(res, "ooooo");
    if (res) {
      ElMessage({
        message: '短信发送成功',
        type: 'success',
      })
      // console.log(99999);
      if (!isopen) {
        donetm(7, () => {
          isopen = false
        })
      }
      isopen = false
    }

  } catch (error) {

    console.log(error);

  }



}


const donetm = (time = 10, cd) => {
  console.log("cd", cd);
  let conut = time
  str.value = `${conut}`,
    console.log("count", conut);
  timer.value = setInterval(() => {
    conut--
    str.value = `${conut}s后发送`
    if (conut <= 0) {
      str.value = '点击发送'
      clearInterval(timer.value)
      if (cd) {
        cd()
      }
      return
    }
  }, 1000)
}
</script>

    